package com.retry.rabbit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * 需要消费者开启重试
 */
@Slf4j
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener.simple.retry",name = "enable",havingValue = "true") //注解规则没测， 请好心人帮我修正
@Configuration
public class ErrorConfig {
    public static final String RETRY_ERROR_QUEUE="retry_error_queue";
    public static final String RETRY_ERROR_EXCHANGE="retry_error_exchange";
    public static final String RETRY_ERROR_ROUTE_KEY="retry_error_route_key";

    /**
     * 创建队列
     */
    @Bean
    public Queue queueError(){
        //                      队列名             是否持久化     是否独占          是都自动删除
        return new Queue(RETRY_ERROR_QUEUE,false,false,true);
    }


    /**
     * 创建的交换机
     */
    @Bean
    public DirectExchange retryErrorExchange(){
        //同理队列，建造者模式也可以在后面加很多属性
        return ExchangeBuilder.directExchange(RETRY_ERROR_EXCHANGE).autoDelete().build();
    }

    /**
     * 绑定关系
     */
    @Bean
    public Binding bindError(){
        return BindingBuilder.bind(queueError()).to(retryErrorExchange()).with(RETRY_ERROR_ROUTE_KEY);
    }

    /**
     * 监听器，如果重试失败会把消息发送到这个队列中
     * @param rabbitTemplate
     * @return
     */
    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        log.info("加载RepublishMessageRecoverer。。。。。");
        return new RepublishMessageRecoverer(rabbitTemplate,RETRY_ERROR_EXCHANGE,RETRY_ERROR_ROUTE_KEY);
    }

}
